package com.jkl.webserver.Web.Controller;

import com.jkl.webserver.Tool.CopyFile;
import com.jkl.webserver.Tool.xFile;
import com.jkl.webserver.Web.Service.WebRegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
public class WebRegisterController {
    private final WebRegisterService registerService;
    private final xFile xfile;
    private final CopyFile copyFile;
    @Autowired
    public WebRegisterController(WebRegisterService registerService, xFile xfile, CopyFile copyFile) {
        this.registerService = registerService;
        this.xfile = xfile;
        this.copyFile = copyFile;
    }
    //网页注册
    @GetMapping(path = "/Register")
    public String registerPage(Model model,HttpServletRequest request){
        model.addAttribute("Web",getLocalHostAddress(request));
        return "views/register/register";
    }

    @GetMapping("/registerRes/{img}")
    public void getRegisterRes(@PathVariable String img, HttpServletResponse response) throws IOException {
        String filePath = xfile.getBasePath() + "/publicBackground/registerRes/" + img;
        response.setHeader("Cache-Control", "max-age=3600");
        response.setContentType("image/png");
        copyFile.byteCopy(filePath, response.getOutputStream());
    }

    @PostMapping(path = "/Register")
    public  String registering(Model model, @RequestParam String username, @RequestParam String password, @RequestParam String email, @RequestParam String verifyCode, HttpServletRequest request) throws Exception {
        model.addAttribute("username",username);
        model.addAttribute("password",password);
        model.addAttribute("email",email);
        if(!verifyCode.toLowerCase().equals(request.getSession().getAttribute("code")))//验证码错误
        {
            model.addAttribute("message1","*验证码错误");
        }
        else
        {
            if(registerService.WebRegister(username,password,email)){
                model.addAttribute("color",true);
                model.addAttribute("message","注册成功");
            }
            else{
                model.addAttribute("color",false);
                model.addAttribute("message","*注册失败,用户已存在");
            }
        }
        model.addAttribute("Web",getLocalHostAddress(request));
        return "views/register/register";
    }
    private String getLocalHostAddress(HttpServletRequest request){
        String scheme = request.getScheme(); // 例如: http
        String serverName = request.getServerName(); // 例如: localhost
        int serverPort = request.getServerPort(); // 例如: 8080
        return scheme+"://"+serverName+":"+serverPort;
    }
}
